package com.bose.bosecmdclient;

import static com.bose.bosecmdclient.R.id.*;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
//import android.net.LocalSocket;
//import android.net.LocalSocketAddress;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.net.Socket;


public class MainActivity extends Activity {

    private static final int MESSAGE_CMD_RESPONSE = 1;

    final Handler mainHandler;
    private Handler threadHandler;
    private CmbClient mCmbClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCmbClient = new CmbClient();

        MyClickListener cl = new MyClickListener();
        findViewById(button_send0).setOnClickListener(cl);
        findViewById(button_send1).setOnClickListener(cl);
        findViewById(button_send3).setOnClickListener(cl);


        findViewById(button_aidl).setOnClickListener(view -> {
            Intent intent = new Intent(MainActivity.this, AidlActivity.class);
            intent.putExtra(AidlActivity.INTENT_SERVICE_NAME_STR, "bosecmd_sys") ;
            startActivity(intent);
        });

        findViewById(button_quit).setOnClickListener(view -> {
            finish();
        });

        recoveryText();
    }


    public void onStop() {
        super.onStop();
        saveText();
        mCmbClient.disConnect();
    }

    private class MyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v){
            final int textId;
            if(v.getId() == button_send0)textId = text0;
            else if(v.getId() == button_send1)textId = text1;
            else if(v.getId() == button_send3)textId = text3;
            else return;

            String ip = null;
            int port = 0;
            String text = null;
            EditText et = findViewById(textId);
            if (null != et) {
                text = et.getText().toString();
            }
            EditText et_ip = findViewById(et_ip_address);
            EditText et_port = findViewById(et_port_id);
            if (null != et_ip) {
                ip = et_ip.getText().toString();
            }
            if (null != et_port) {
                try {
                    port = Integer.parseInt(et_port.getText().toString());
                } catch (NumberFormatException e) {
                    ;
                }
            }

        final String sIp = ip;
        final int sPort = port;
        final String cmd = text;
            sendCmd(cmd, sIp, sPort);
        }
    }


    class ThreadHandler extends Handler {
        Activity thisActivity;
        ThreadHandler(Looper looper, Activity activity) {
            super(looper);
            thisActivity = activity; //todo make it as weak reference
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_CMD_RESPONSE) {
                //Toast.makeText(thisActivity, "Thread, response:" + msg.obj, Toast.LENGTH_SHORT).show();
                Message m = new Message();
                m.obj = msg.obj;
                m.what = MESSAGE_CMD_RESPONSE;
                m.setTarget(mainHandler);
                mainHandler.sendMessageDelayed(m, 100);
            }
        }
    }

    public MainActivity() {
        this.mainHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == MESSAGE_CMD_RESPONSE) {
                    //Toast.makeText(MainActivity.this, "Main, response:" + msg.obj, Toast.LENGTH_SHORT).show();
                    EditText reponseView = findViewById(text_response);
                    reponseView.setText(msg.obj.toString());
                }
            }
        };
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                Looper threadLopper = Looper.myLooper();
                threadHandler = new ThreadHandler(threadLopper, MainActivity.this);
                Looper.loop();
            }
        }.start();
    }

    private void sendCmd(String cmdStr, String ip, int port) {
        if(threadHandler == null) return;
        if(cmdStr == null || cmdStr.length() <= 0) return;
        if('*' == cmdStr.charAt(0)) {
            cmdStr += "\r";
        }
        byte[] cmd = cmdStr.getBytes();
        new Thread(){
            @Override
            public void run() {
                Socket sock = mCmbClient.connect(ip, port);
                CmbClient.sendData(sock, cmd);
                String resp = CmbClient.receiveData(sock);
                if (null != resp && resp.length() > 0) {
                    Message msg = new Message();
                    msg.what = MESSAGE_CMD_RESPONSE;
                    msg.obj = resp;
                    msg.setTarget(threadHandler);
                    msg.sendToTarget();
                }
                //mainHandler.sendMessage(msg);
            }
        }.start();
    }


    private void putEtString(SharedPreferences.Editor editor, String IdString, int textId) {
        String text;
        EditText et = findViewById(textId);
        if (null != et) {
            text = et.getText().toString();
            editor.putString(IdString,text);
        }
    }

    private void recoveryEtString(SharedPreferences sp, String IdString, int textId) {
        String text = sp.getString(IdString, "");
        EditText et = findViewById(textId);
        if (null != et && text.length() > 0) {
            et.setText(text);
        }
    }

    private void saveText() {
        SharedPreferences sharedPreferences=getSharedPreferences("cmdData",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        putEtString(editor, "text0", text0);
        putEtString(editor, "text1", text1);
        putEtString(editor, "text3", text3);
        putEtString(editor, "et_ip_address", et_ip_address);
        putEtString(editor, "et_port_id", et_port_id);
        boolean bol=editor.commit();

    }

    public void recoveryText() {
        SharedPreferences sharedPreferences=getSharedPreferences("cmdData",Context.MODE_PRIVATE);
        recoveryEtString(sharedPreferences, "text0", text0);
        recoveryEtString(sharedPreferences, "text1", text1);
        recoveryEtString(sharedPreferences, "text3", text3);
        recoveryEtString(sharedPreferences, "et_ip_address", et_ip_address);
        recoveryEtString(sharedPreferences, "et_port_id", et_port_id);

    }
}
